package org.robot.scm.platform.server.handler;

import static org.robot.scm.platform.server.LockKey.LOCK_KEY;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.robot.scm.infra.RedisCacheHelper;
import org.robot.scm.platform.server.common.DefaultRunner;
import org.robot.scm.pojos.config.BaseConfig;
import org.robot.scm.pojos.enums.PlatformEnum;
import org.robot.scm.pojos.platform.server.ExecuteParam;
import org.robot.scm.utils.JsonHelper;

/**
 * 清理三个月前的数据
 */
@Slf4j
@NoArgsConstructor
public class CleanDataHandler extends BaseHandler implements HttpHandler {

    @Override
    public String getUri() {
        return "/cleanData";
    }

    @Override
    public void handle(HttpExchange exchange) throws IOException {
        if (!exchange.getRequestMethod().equalsIgnoreCase("POST")) {
            sendFailureResponse(exchange, "请求非法");
            return;
        }

        // 并发校验
        String locker = RedisCacheHelper.get(LOCK_KEY);
        if (StringUtils.isNotBlank(locker)) {
            sendFailureResponse(exchange, "有任务正在执行中");
            return;
        }
        String requestBody = new BufferedReader(new InputStreamReader(exchange.getRequestBody(), StandardCharsets.UTF_8)).lines().collect(Collectors.joining("\n"));
        ExecuteParam executeParam = JsonHelper.toObject(requestBody, ExecuteParam.class);
        executeParam.setIsCleanTask(Boolean.TRUE);
        executeParam.checkClean();

        // 替换sql中的占位符${cleanDate}为 2024-01-01 00:00:00 且记录行信息
        int total = 0;
        File targetFile = new File("assets/telegram/" + executeParam.getFileKey() + ".sql");
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(Files.newInputStream(targetFile.toPath()), StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                if (StringUtils.isBlank(line)) {
                    continue;
                }
                total++;
            }
            executeParam.setFileLine(total);
        } catch (IOException e) {
            sendFailureResponse(exchange, e.getMessage());
        }
        RedisCacheHelper.put(LOCK_KEY, JsonHelper.toJSONString(executeParam));

        // 处理清理任务
        CompletableFuture.runAsync(() -> new DefaultRunner().start(config(PlatformEnum.SQL), executeParam));
        sendSuccessResponse(exchange, "清理成功");
    }

}
